
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import agend.agents.AgendAgent;
import agend.agents.RegistrationAgent;
import agend.db.DBQuery;
import jade.Boot;
import jade.core.Profile;
import jade.core.ProfileImpl;
import jade.core.Runtime;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;
import jade.wrapper.ContainerController;
import jade.wrapper.StaleProxyException;


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {		
		
		List<String[]> listParam = new ArrayList<String[]>();
		
		try {
			
			ResultSet resultSet = DBQuery.getPreparedStatement().executeQuery();
			
			while(resultSet.next())
			{
				String[] param = new String[2];
				
				param[0] = resultSet.getString(2);
				param[1] = resultSet.getString(3);
				
				listParam.add(param);
			}
			
		} catch (SQLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		Runtime runtime = Runtime.instance();
		
		runtime.setCloseVM(true);
		
		Profile profileMain = new ProfileImpl();
		profileMain.setParameter(Profile.PLATFORM_ID,"ServerPlatform");
		
		AgentContainer containerMain = runtime.createMainContainer(profileMain);
		
		createMonitoringAgents(containerMain);
		
		for( String [] param : listParam ){				
				
				String name = param[0].replace("@", "#");
				
				AgentController agent;
				try {
					agent = containerMain.createNewAgent(name, AgendAgent.class.getName(), param);
					agent.start();
				} catch (StaleProxyException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}				
		}	
								
				
			
		
		try {
			
			AgentController registration = containerMain.createNewAgent("registration", RegistrationAgent.class.getName(), new Object[0]);
			
			registration.start();
			
		} catch (StaleProxyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private static void createMonitoringAgents(ContainerController mc) {

		System.out.println("Launching the rma agent on the main container ...");
		AgentController rma;

		try {
			rma = mc.createNewAgent("rma", "jade.tools.rma.rma", new Object[0]);
			rma.start();
		} catch (StaleProxyException e) {
			e.printStackTrace();
			System.out.println("Launching of rma agent failed");
		}

		System.out.println("Launching  Sniffer agent on the main container...");
		AgentController snif=null;

		try {
			snif= mc.createNewAgent("sniffeur", "jade.tools.sniffer.Sniffer",new Object[0]);
			snif.start();

		} catch (StaleProxyException e) {
			e.printStackTrace();
			System.out.println("launching of sniffer agent failed");

		}	
	}

}
